import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { startOfMonth, endOfMonth, subMonths, format } from 'date-fns';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const siteId = searchParams.get('siteId');
    const months = parseInt(searchParams.get('months') || '6', 10);
    const startDate = startOfMonth(subMonths(new Date(), months - 1));
    const endDate = endOfMonth(new Date());

    // 获取基础统计数据
    const [
      totalExpenses,
      expensesByType,
      monthlyExpenses,
      siteExpenses,
      recentExpenses
    ] = await Promise.all([
      // 总支出
      prisma.expense.aggregate({
        where: {
          ...(siteId && { siteId }),
          paymentDate: {
            gte: startDate,
            lte: endDate,
          },
        },
        _sum: {
          amount: true,
        },
      }),

      // 按类型统计
      prisma.expense.groupBy({
        by: ['type'],
        where: {
          ...(siteId && { siteId }),
          paymentDate: {
            gte: startDate,
            lte: endDate,
          },
        },
        _sum: {
          amount: true,
        },
      }),

      // 按月统计
      prisma.expense.groupBy({
        by: ['paymentDate'],
        where: {
          ...(siteId && { siteId }),
          paymentDate: {
            gte: startDate,
            lte: endDate,
          },
        },
        _sum: {
          amount: true,
        },
        orderBy: {
          paymentDate: 'asc',
        },
      }),

      // 按工地统计
      prisma.expense.groupBy({
        by: ['siteId'],
        where: {
          ...(siteId && { siteId }),
          paymentDate: {
            gte: startDate,
            lte: endDate,
          },
        },
        _sum: {
          amount: true,
        },
      }),

      // 最近支出记录
      prisma.expense.findMany({
        where: {
          ...(siteId && { siteId }),
          paymentDate: {
            gte: startDate,
            lte: endDate,
          },
        },
        orderBy: {
          paymentDate: 'desc',
        },
        take: 10,
        include: {
          site: {
            select: {
              name: true,
              status: true,
            },
          },
        },
      }),
    ]);

    // 获取工地信息
    const sites = await prisma.site.findMany({
      where: {
        id: {
          in: siteExpenses.map(e => e.siteId),
        },
      },
      select: {
        id: true,
        name: true,
        status: true,
        contractAmount: true,
      },
    });

    // 按月份合并统计数据
    const monthlyStats = new Map<string, number>();
    monthlyExpenses.forEach(e => {
      const month = format(e.paymentDate, 'yyyy-MM');
      monthlyStats.set(
        month,
        (monthlyStats.get(month) || 0) + (e._sum.amount || 0)
      );
    });

    // 处理统计数据
    const summary = {
      total: totalExpenses._sum.amount || 0,
      byType: expensesByType.reduce((acc, curr) => {
        acc[curr.type] = curr._sum.amount || 0;
        return acc;
      }, {} as Record<string, number>),
      monthly: Array.from(monthlyStats.entries())
        .map(([month, amount]) => ({
          month,
          amount,
        }))
        .sort((a, b) => a.month.localeCompare(b.month))
        .slice(-months),
      bySite: siteExpenses.map(e => {
        const site = sites.find(s => s.id === e.siteId);
        return {
          siteId: e.siteId,
          siteName: site?.name,
          status: site?.status,
          contractAmount: site?.contractAmount || 0,
          expenseAmount: e._sum.amount || 0,
        };
      }),
      recentExpenses,
    };

    return NextResponse.json(summary);
  } catch (error) {
    console.error('获取支出汇总失败:', error);
    return NextResponse.json(
      { error: '获取支出汇总失败' },
      { status: 500 }
    );
  }
} 